layui.use(top.layuiuse,
    function () {
        var form = layui.form;
        var watermark = layui.watermark;
        var tabs = layui.tabs;
        var kaPublic = layui.kaPublic;
        var kahtml = layui.kahtml;
        var $ = layui.jquery;
        var kaAjax = layui.kaAjax;
        var kaBgUrl = layui.kaBgUrl;
        var kaLog = layui.kaLog;
        var kaLanguage = layui.kaLanguage;
        var kaForm = layui.kaForm;
        var kaInterval = layui.kaInterval;
        var kaPhonenVerCode = layui.kaPhonenVerCode;
        var layuiFormId = "login-form-val-filter";
        //公共
        var bodyUrl = kaPublic.initBodySetUp();
        //加载水印
        loadingWatermark(watermark)
        //加载登录页面
        var registerkeyData = [];
        var tabsLoginHeader = [];
        var tbasLoginBody = [];
        var TABS_ID = ""; // tab 页面ID
        var scanCodeErrorList = [];// 扫码错误页面
        var scanCodeSuccessList = [];// 扫码成功页面
        var loginAccountList = [];// 账号登录页面
        var loginPhoneList = [];// 手机号登录页面
        var loginScanCodeList = [];// 扫码登录页面
        var languageTypeDivId = "";// 语言类型渲染Id
        var logo = {};// Logo
        var loginTitle = {};//登录页面标题
        var tenantHtml = {};//租户Html 选择
        //请求后台配置
        kaAjax.ajax(kaBgUrl.url("loginSetUp"), function (rs) {
            if (rs.code == 200) {
                registerkeyData = rs.data.registerkey; // 注册页面 ID
                tabsLoginHeader = rs.data.tabsLoginHeader;
                tbasLoginBody = rs.data.tbasLoginBody;
                TABS_ID = rs.data.tabsId; // 页面ID
                scanCodeErrorList = rs.data.scanCodeError; // 扫码错误页面
                scanCodeSuccessList = rs.data.scanCodeSuccess; // 扫码成功页面
                loginAccountList = rs.data.loginAccount; // 账号登录页面
                loginPhoneList = rs.data.loginPhone; // 手机号登录页面
                loginScanCodeList = rs.data.loginScanCode; // 扫码登录页面
                languageTypeDivId = rs.data.languageTypeDivId; // 语言类型ID
                logo = rs.data.logo; // logo配置
                loginTitle = rs.data.loginTitle; // 登录页面标题
                tenantHtml = rs.data.tenant; // 登录页面标题 
            }
        })
        // 获取语言类型
        kaLanguage.renderingOption("languageSelect", function (rs) {
            if (rs.code == 200) {
                var languageTypeData = rs.data;//语言类型数据
                $("#" + languageTypeDivId).html(kaPublic.loadOptionHtml(languageTypeData, "id", "name"));
                form.render();
                var languageTypeCurrent = localStorage.getItem("kaLanguageTypeCurrent");
                if (languageTypeCurrent == undefined || languageTypeCurrent == null || languageTypeCurrent == "" || languageTypeCurrent == "null") {
                    languageTypeCurrent = 1;
                }
                form.val(layuiFormId, { "language": languageTypeCurrent });
                form.on('select(' + languageTypeDivId + ')', function (data) {
                    var value = data.value; // 获得被选中的值
                    localStorage.setItem("kaLanguageTypeCurrent", value);
                    kaLanguage.loadingValue(value);
                    window.location.reload();
                });
            }
        });
        //设置logo
        $("#" + logo.id).attr("src", logo.src);
        //设置登录标题
        $("#" + loginTitle.id).html(loginTitle.html);
        //获取租户按钮
        kaAjax.ajax(kaBgUrl.url("tenant"), function (rs) {
            if (rs.code == 200) {
                var tenantData = rs.data;//语言类型数据
                $("#" + tenantHtml.id).html(kaPublic.loadOptionHtml(tenantData, "tenantId", "tenantName"));
                form.render();
                for (var i in tenantData) {
                    if (tenantData[i].defaulStatus == 1) {
                        form.val(layuiFormId, { "tenantId": tenantData[i].id });
                        break;
                    }
                }
                form.on('select(' + tenantHtml.id + ')', function (data) {
                    var formval = form.val(layuiFormId);
                    if (formval.loginmode == 0) { // 账号登录
                        form.val(layuiFormId, {
                            "username": "",
                            "password": "",
                            "code": "",
                            "automaticLogon": false
                        });
                    } else if (formval.loginmode == 1) { // 手机号登录
                        form.val(layuiFormId, {
                            "phonenumber": "",
                            "codePhonenumber": ""
                        });
                    } else if (formval.loginmode == 2) { // 扫码登录
                        // form.val(layuiFormId, {
                        //     "phonenumber": "",
                        //     "codePhonenumber": ""
                        // });
                    }

                    kaLog.print("success", [data]);
                });
            }
        })
        //注册页面
        var registerkey = kaRegisterPrimaryKey.registerId(registerkeyData); //注册页面ID
        var appPhone = kaPublic.isAppPhoneOrExe();// 判断页面手机端 
        if (appPhone.code == "200" && appPhone.type == "APP") { // 手机端
            var th = [], tb = [];
            for (var i in tabsLoginHeader) {
                if (tabsLoginHeader[i].phoneBoolean) {
                    th.push(tabsLoginHeader[i]);
                    tb.push(tbasLoginBody[i]);
                }
            }
            tabsLoginHeader = th;
            tbasLoginBody = tb;
        } else { // PC端 EXE
            if (appPhone.type == "EXE") { } else { }
        }
        // 渲染标签 
        tabs.render({
            elem: '#' + TABS_ID,
            header: tabsLoginHeader,
            body: tbasLoginBody,
            index: 0
        })
        // 获取扫码编码内容
        function getScanCodeValue(qrcodeDivId) {
            var scanCodeValue = "";
            const userAgent = navigator.userAgent; // 获取用户代理字符串
            const screenWidth = screen.width;       // 获取屏幕宽度
            const screenHeight = screen.height;     // 获取屏幕高度
            const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; // 获取时区
            var formval = layui.form.val(layuiFormId);
            formval["userAgent"] = userAgent;
            formval["screenWidth"] = screenWidth;
            formval["screenHeight"] = screenHeight;
            formval["timezone"] = timezone;
            kaAjax.ajax(kaBgUrl.url("getScanCodeValue"), function (rs) {
                if (rs != null && rs != undefined) {
                    if (rs.code == 200) {
                        scanCodeValue = rs.data;
                        sessionStorage.setItem("scanCodeWaitTime", new Date().getTime());
                        sessionStorage.setItem("scanCodeWaitValue", scanCodeValue);
                        $("#saoMaQrcodeCode").val(scanCodeValue);
                        // 扫码登录登录监听
                        getScanCodeWait(qrcodeDivId);
                    }
                }
            }, formval)
            return scanCodeValue;
        }
        // 扫码登录登录监听
        function getScanCodeWait(qrcodeDivId) {
            var res = {};
            res["intervalName"] = "scanCodeWaitInterval"; // 手機號碼
            res["sessionStorageValue"] = "scanCodeWaitValue"; // sessionStorage Name
            res["sessionStorageTime"] = "scanCodeWaitTime"; // sessionStorage Name
            res["qrcodeDivId"] = qrcodeDivId; // sessionStorage Name
            kaInterval.init(res.intervalName, res, function (resData) {
                var scanCodeWaitValue = sessionStorage.getItem(resData.sessionStorageValue);
                if (scanCodeWaitValue == undefined || scanCodeWaitValue == null || scanCodeWaitValue == "") {
                    kaInterval.clear(resData.intervalName, resData);
                    return false;
                }
                var scanCodeWaitTime = sessionStorage.getItem(resData.sessionStorageTime);
                if (scanCodeWaitTime == undefined || scanCodeWaitTime == null || scanCodeWaitTime == "") {
                    kaInterval.clear(resData.intervalName, resData);
                    return false;
                }
                // 处理业务判断停止
                kaInterval.judge(60, scanCodeWaitTime, resData, function (resDataData) {
                    $("#getScanCodeWaitRefreshClick").unbind(); //先取消綁定事件
                    //过期
                    var errorSaoMaoHtmlData = {
                        id: registerkey.ids[3],
                        list: scanCodeErrorList // 账号登录配置数据
                    }
                    errorSaoMaoHtmlData.list[0].qrcodeDivId = resDataData.qrcodeDivId;
                    $("#" + resDataData.qrcodeDivId).prepend(kahtml.getTemplateHtml("loginScanCodeError", errorSaoMaoHtmlData, 1));
                    // 渲染
                    kahtml.refreshPublic(function () {
                        //绑定按钮
                        $("#getScanCodeWaitRefreshClick").bind("click", function () {
                            var scanCodeValue = getScanCodeValue($(this).attr("qrcodeDivId"));
                            produceQrcode($(this).attr("qrcodeDivId"), scanCodeValue);
                        });
                    });
                    // 清理
                    kaInterval.clear(resDataData.intervalName, resDataData);
                }, function (resDataData, syxx) {
                    var formval = layui.form.val(layuiFormId);
                    kaAjax.ajax(kaBgUrl.url("getScanCodeVerify"), function (rs) {
                        if (rs.code == 200) {
                            var data = rs.data;
                            if (data.status == 1) { // 已经扫码
                                kaInterval.clear(resDataData.intervalName, resDataData, function (resDataDataData) {
                                    var successSaoMaoHtmlData = {
                                        id: registerkey.ids[4],
                                        list: scanCodeSuccessList // 账号登录配置数据
                                    }
                                    var correspondingDevice = data.correspondingDevice;
                                    $("#" + resDataDataData.qrcodeDivId).prepend(kahtml.getTemplateHtml("loginScanCodeSuccess", successSaoMaoHtmlData, 1));
                                    $("#correspondingDevice").val(correspondingDevice);
                                    // 跳转
                                    layui.kaMsg.jumpCountdown(3, "手机已经扫码", function () {
                                        $("#loginScanCodeButtonId").click();
                                    })
                                });
                            } else if (data.status == 0) { // 等待中
                                console.log(syxx);
                            } else if (data.status == -1) { //已经过期
                                kaInterval.clear(resDataData.intervalName, resDataData, function (resDataDataData) {
                                    $("#getScanCodeWaitRefreshClick").unbind(); //先取消綁定事件
                                    var errorSaoMaoHtmlData = {
                                        id: registerkey.ids[3],
                                        list: scanCodeErrorList // 账号登录配置数据
                                    }
                                    errorSaoMaoHtmlData.list[0].qrcodeDivId = resDataDataData.qrcodeDivId;
                                    $("#" + resDataDataData.qrcodeDivId).prepend(kahtml.getTemplateHtml("loginScanCodeError", errorSaoMaoHtmlData, 1));
                                    // 渲染
                                    kahtml.refreshPublic(function () {
                                        //绑定按钮
                                        $("#getScanCodeWaitRefreshClick").bind("click", function () {
                                            var scanCodeValue = getScanCodeValue($(this).attr("qrcodeDivId"));
                                            produceQrcode($(this).attr("qrcodeDivId"), scanCodeValue);
                                        });
                                    });

                                });
                            }
                        }
                    }, formval)
                })
            });
        }
        // 生成二维码
        function produceQrcode(qrcodeDivId, scanCodeValue) {
            $("#" + qrcodeDivId).html("");
            $("#" + qrcodeDivId).qrcode({
                render: "canvas", //也可以替换为table
                width: 164,
                height: 164,
                text: scanCodeValue
            });
        }
        // 切换登录事件
        tabs.on('afterChange(' + TABS_ID + ')', function (data) {
            if (registerkey.judge) {
                if (data.index == 0) {
                    // 清除 kaInterval 
                    var res1 = { intervalName: "phonenVerCodeButton" };
                    var res2 = { intervalName: "scanCodeWaitInterval" };
                    if (kaInterval.getValue(res1.intervalName) != "") { kaInterval.clear(res1.intervalName, res1); }
                    if (kaInterval.getValue(res2.intervalName) != "") { kaInterval.clear(res2.intervalName, res2); }
                    // 清除 Tabs 渲染的Html
                    $("#" + registerkey.ids[1]).html("");
                    $("#" + registerkey.ids[2]).html("");
                    // 开始配置第一个Tab
                    var loginAccountHtmlData = {
                        id: registerkey.ids[0],
                        list: loginAccountList // 账号登录配置数据
                    }
                    kahtml.getTemplateHtml(tabsLoginHeader[0].templateHtmlId, loginAccountHtmlData);
                    form.render();
                    //获取驗證碼按钮
                    $("#" + loginAccountList[0].captchaImageKBQ).unbind(); //先取消綁定事件
                    $("#" + loginAccountList[0].captchaImageKBQ).click(function () {
                        kaAjax.ajax(kaBgUrl.url("captchaImage"), function (rs) {
                            if (rs.code == 200) {
                                var imgsrc = "data:image/gif;base64," + rs.img;//驗證碼
                                $("#" + loginAccountList[0].captchaImage).attr("src", imgsrc);
                                $("#uuid").val(rs.uuid);
                            }
                        })
                    });
                    // 验证码看不清
                    $("#" + loginAccountList[0].captchaImageKBQ).click();
                    //立即注册
                    $("#" + loginAccountList[0].registerAccountId).unbind(); //先取消綁定事件
                    $("#" + loginAccountList[0].registerAccountId).click(function () {
                        layer.open({
                            type: 2,
                            title: '立即申请',
                            shadeClose: true,
                            shade: [0.6, '#FFF'],
                            area: ['480px', '480px'],
                            content: './formRendering.html?id=1' // iframe 的 url
                        });
                    });
                    // 记住密码
                    form.on('checkbox(' + loginAccountList[0].automaticLayFilter + ')', function (data) {
                        var elem = data.elem; // 获得 checkbox 原始 DOM 对象
                        layer.msg(elem.checked ? "开启记住密码" : "关闭记住密码");
                    });
                    // 设置 记住密码
                    var al = localStorage.getItem(loginAutomaticLogonName);
                    if (!(al == undefined || al == null || al == "")) {
                        form.val(layuiFormId, JSON.parse(al));
                    }
                    var systemType = bodyUrl.systemType;
                    if(systemType == undefined || systemType == null || systemType == ""){
                        systemType = "PC";
                    }
                    $("#systemType").val(systemType);
                    // 登 录 提 交
                    kaForm.submit("loginAccount", "loginAccount", "login");
                } else if (data.index == 1) {
                    // 清除 kaInterval 
                    var res1 = { intervalName: "phonenVerCodeButton" };
                    var res2 = { intervalName: "scanCodeWaitInterval" };
                    if (kaInterval.getValue(res1.intervalName) != "") { kaInterval.clear(res1.intervalName, res1); }
                    if (kaInterval.getValue(res2.intervalName) != "") { kaInterval.clear(res2.intervalName, res2); }

                    // 清除 Tabs 渲染的Html
                    $("#" + registerkey.ids[1]).html("");
                    $("#" + registerkey.ids[2]).html("");
                    var loginPhoneHtmlData = {
                        id: registerkey.ids[1],
                        list: loginPhoneList // 手机号码登录配置数据
                    }
                    kahtml.getTemplateHtml(tabsLoginHeader[1].templateHtmlId, loginPhoneHtmlData);
                    form.render();
                    //立即注册
                    $("#" + loginPhoneList[0].registerAccountId).unbind(); //先取消綁定事件
                    $("#" + loginPhoneList[0].registerAccountId).click(function () {
                        layer.open({
                            type: 2,
                            title: '立即申请',
                            shadeClose: true,
                            shade: [0.6, '#FFF'],
                            area: ['480px', '480px'],
                            content: './formRendering.html?id=1' // iframe 的 url
                        });
                    });
                    //获取手机驗證碼按钮
                    kaPhonenVerCode.init(loginPhoneList[0].PhonenVerCodeId, loginPhoneList[0].accountId, layuiFormId, 1);
                    var systemType = bodyUrl.systemType;
                    if(systemType == undefined || systemType == null || systemType == ""){
                        systemType = "PC";
                    }
                    $("#systemType").val(systemType);
                    // 登 录 提 交
                    kaForm.submit("loginPhone", "loginPhone", "login");
                } else if (data.index == 2) {
                    // 清除 kaInterval 
                    var res1 = { intervalName: "phonenVerCodeButton" };
                    var res2 = { intervalName: "scanCodeWaitInterval" };
                    if (kaInterval.getValue(res1.intervalName) != "") { kaInterval.clear(res1.intervalName, res1); }
                    if (kaInterval.getValue(res2.intervalName) != "") { kaInterval.clear(res2.intervalName, res2); }
                    // 清除 Tabs 渲染的Html
                    $("#" + registerkey.ids[1]).html("");
                    $("#" + registerkey.ids[2]).html("");
                    loginScanCodeList[0].qrcodeDivUUID = kaPublic.uuidStr();
                    var loginScanCodeHtmlData = {
                        id: registerkey.ids[2],
                        list: loginScanCodeList // 循环数据
                    }
                    kahtml.getTemplateHtml(tabsLoginHeader[2].templateHtmlId, loginScanCodeHtmlData);
                    // 登 录 提 交
                    var systemType = bodyUrl.systemType;
                    if(systemType == undefined || systemType == null || systemType == ""){
                        systemType = "PC";
                    }
                    $("#systemType").val(systemType);
                    kaForm.submit("loginScanCode", "loginScanCode", "login");
                    // 扫码登录登录获取值并启动监听
                    var scanCodeValue = getScanCodeValue(loginScanCodeHtmlData.list[0].qrcodeDivId);
                    produceQrcode(loginScanCodeHtmlData.list[0].qrcodeDivId, scanCodeValue);
                }
            }
        });
        if (appPhone.code == "200" && appPhone.type == "APP") { // 手机端
            tabs.change(TABS_ID, 1);
        } else { // PC端 EXE
            tabs.change(TABS_ID, 0);
        }
    }
)